/***********************************************************
                   save_contig_fpc
************************************************************/
#include "fpp.h"
#include <fcntl.h>
#include <float.h>
#include <sys/stat.h>

extern char Zmap[50];
extern int Zg, Zimin, Zimax;
extern float Zfmin, Zfmax;
extern void getdatehead();
extern void Zmap_ace();
extern FILE *graphQueryOpen();
extern void suffixremove();
extern int save_fpc();

static FILE *fpace;

/********************************************************************/
static int save_fpc_ctg(int num)
{  
  CLONE *clone;
  struct remark *pointer;
  struct marker *marker;
  struct markertop *topmarkerptr;
  struct marker *markerptr;
  char out2[100], type[30],path[MAXPATHLEN];
  int  nbands;
  int i, c;
  struct stat stbuf;

  sprintf(path,"%s/%s.fpc",mergedir,mergefile);
   
  if(stat(path,&stbuf)!=-1){
    if(stbuf.st_blocks == 0){
      printf("Creating file %s\n",path);
      printf("Ctg%d data written to file\n",num);
      if((fpace = fopen(path,"a")) ==NULL) {
	  printf("FAILED TO open %s\n",path);
          return 0;
      }
      if(bands) nbands = arrayMax(bands);
      else nbands = tot_bands;
      
      fprintf (fpace, "// fpc project %s\n", fileName) ;
      getdatehead(out2);
      fprintf (fpace, "// %s\n", out2) ;
      fprintf (fpace, "// Clones %d  Markers %d  Bands %d\n\n", contigs[num].count, 
	       contigs[num].markers, nbands) ;
    }
    else{
      printf("Appending ctg%d data to file %s\n",num,path);
      printf("NB The clones & marker counts in header will initially be wrong - its ok\n");
      if ((fpace = fopen(path,"a")) == NULL) {
	printf("FAILED TO open %s\n",path);
        return 0;
      } 
      fprintf(fpace,"\nClonedata\n\n");
    }
  }
  else{
    printf("ERROR getting stat for %s\n",path);
    return 0;
  }
  sprintf(Zmap,"\"ctg%d\"",num);

  for (c= contigs[num].start; c != -1; c = clone->next) 
  {
    clone = arrp(acedata, c, CLONE); 
    fprintf(fpace,"\n%s : \"%s\"\n",clonetype[clone->class],clone->clone);
    strcpy(type,clonetype[clone->class]);
    
    fprintf(fpace,"Map %s Ends Left %d.000\n", Zmap, clone->x);
    fprintf(fpace,"Map %s Ends Right %d.000\n",Zmap, clone->y);
    if (Zimin > clone->x) Zimin = clone->x;
    if (Zimax < clone->y) Zimax = clone->y;
    
    if(clone->fp != NULL){
      if(clone->fp->fpchar[0] != ' ')
        fprintf(fpace,"Fp_number \"%s\"\n",clone->fp->fpchar);
      fprintf(fpace,"Gel_number    %s\n",clone->fp->gelname);
      fprintf(fpace,"Bands  %d %d\n",clone->fp->b1,clone->fp->b2);
    }
    if(clone->seqstat > 0) /* ADD 27jul00 */
      fprintf(fpace,"Shotgun %s %s\n",
           seqtype[clone->seqtype], seqstat[clone->seqstat]);

    if(clone->mattype > PSPARENT){ /* i.e. if its a match */
      if(clone->mattype & EXACT )
	fprintf (fpace,"Exact_match_to_%s \"%s\"\n", type, clone->match) ;
      else if(clone->mattype & APPROX)
	fprintf (fpace,"Approximate_match_to_%s \"%s\"\n", type, clone->match) ;	
      else if(clone->mattype & PSEUDO)
	fprintf (fpace,"Pseudo_match_to_%s \"%s\"\n", type, clone->match) ;	
    }    
    pointer=clone->remark;
    while(pointer!=NULL){
	fprintf(fpace,"Remark \"%s\"\n", pointer->message) ;
      pointer = pointer->next;
    }
    pointer=clone->fp_remark;
    while(pointer!=NULL){
	fprintf(fpace,"Fpc_remark \"%s\"\n", pointer->message) ;
      pointer = pointer->next;
    }

    if(clone->marker !=NULL){
      topmarkerptr = clone->marker;
      while(topmarkerptr != NULL){ /*for each marker */
        markerptr = arrp(markerdata,topmarkerptr->markerindex,MARKER);
        if(markerptr != NULL){ 
          markerptr->status = 100;
          if(topmarkerptr->weak)
            fprintf(fpace,"Positive_%s_weak \"%s\"\n",
                         markertype[markerptr->type],markerptr->marker);
          else
            fprintf(fpace,"Positive_%s \"%s\"\n",
                         markertype[markerptr->type],markerptr->marker);
        }
        topmarkerptr = topmarkerptr->nextmarker;
      }
    }
    if(clone->creation_date.year != 0) 
    fprintf(fpace,"Creation_date %d %d %d %d %d \n",
                         clone->creation_date.year,clone->creation_date.month,
	 clone->creation_date.day,clone->creation_date.hour,clone->creation_date.minute);
    else {
      fprintf(fpace,"Creation_date %d \n",clone->creation_date.year);
    }
    if(clone->modified_date.year != 0)
    fprintf(fpace,"Modified_date %d %d %d %d %d \n",
                         clone->modified_date.year,clone->modified_date.month
	    ,clone->modified_date.day,clone->modified_date.hour,clone->modified_date.minute);
    else
      fprintf(fpace,"Modified_date %d \n",clone->modified_date.year);
  }
  fprintf(fpace,"\nMarkerdata\n\n");

  for (i=0;i<arrayMax(markerdata);i++){
    marker = arrp(markerdata,i,MARKER);
    if (marker->status!=100) continue;
    marker->status = AUTO;
    fprintf(fpace,"Marker_%s : \"%s\"\n",markertype[marker->type],marker->marker);

    if(marker->anchor){
      if(marker->anchor_bin[0] != '\0'){
	fprintf(fpace,"Anchor_bin \"%s\"\n",marker->anchor_bin);
      }
      if(marker->frame_type==FRAME) 
        fprintf(fpace,"Anchor_pos %7.1f F\n",marker->anchor_pos);
      else
        fprintf(fpace,"Anchor_pos %7.1f P\n",marker->anchor_pos);
    }

    pointer=marker->remark;
    while(pointer!=NULL){
	fprintf(fpace,"Remark \"%s\"\n", pointer->message) ;
      pointer = pointer->next;
    }
    fprintf(fpace,"Creation_date %d %d %d %d %d \n",
           marker->creation_date.year,marker->creation_date.month,
           marker->creation_date.day,marker->creation_date.hour,
           marker->creation_date.minute);
    fprintf(fpace,"Modified_date %d %d %d %d %d \n",
              marker->modified_date.year,marker->modified_date.month,
              marker->modified_date.day,marker->modified_date.hour,
              marker->modified_date.minute);
    fprintf(fpace,"\n");
  }
  fclose(fpace);
  return 1;
}

/********************************************************************/
static int check2ctg(char *temp)
{
  int result;

  if(sscanf(temp,"%d",&result)){
    if(result<= max_contig){
      if(contigs[result].count!=0)
	return result;
      else
	printf("There are no clones in this contig\n");
    }
    else
      printf("Must be lower than the max contig\n");
  }
  else
    printf("Please input an integer\n");
  return -1;
}

/********************************************************************/
static void sub_ctg()
{
  int ctg=0;

  if(!dataloaded){   
     fprintf(stdout,"No FPC project loaded.\n");
     return;
  }
  ctg = check2ctg(req2ctg);
  if(ctg > -1)  {
     if((fpace = graphQueryOpen(mergedir,mergefile,"fpc","a","fpc filename")) != NULL) {
        fclose(fpace);
        save_fpc_ctg(ctg);
     }
  }
}

/********************************************************************/
static void request2ctg(char *temp)
{	       
  int ctg=0;

  ctg = check2ctg(temp);
}

/********************************************************************/
void save_as_fpc()
{
  
  if(graphActivate(gsubmit)){ 
    graphClear();
    graphPop();
  }
  else{ 
    gsubmit = graphCreate (TEXT_FIT,"Save Contig as FPC",.2,.2,.3,.16) ;
  }
  
  graphText("Contig:",2.0,2.0);
  graphTextEntry(req2ctg, 6, 9.0, 2.0,request2ctg); 
  graphButton("Save",sub_ctg,16.0,2.0);
  graphButton("Close",graphDestroy,5.0,4.0);
  graphRedraw();
}
/********************************************************************
                  DEF: save_fpc_in_newfile
called from File... "Save FPC as..."
creates new file
*******************************************************************/
void save_fpc_in_newfile(ctg)
{
  char buf[DIR_BUFFER_SIZE*2];
  char timestampTemp[255];
  FILE *fp;
  char fileTemp[FIL_BUFFER_SIZE] ;
  char dirTemp[DIR_BUFFER_SIZE] ;

  sprintf(mergefile,"%s.fpc",mergefile);

  printf("Enter filename without a \'.\' in it. Do not put a .fpc suffix.\n");
  if(!(fp = graphQueryOpen(mergedir,mergefile,
           "fpc","a","New FPC filename"))) return;
  suffixremove(mergefile);
  if (strcmp(fileName,mergefile)==0) {
     printf("Using the same file %s. Abort operation.\n",mergefile);
     return;
  }

  fclose(fp);
  if(strlen(mergedir)>0) sprintf(buf, "%s/%s", mergedir, mergefile);
  else sprintf(buf,"%s",mergefile);

  okaytowrite = TRUE;
  strcpy(fileTemp, fileName);
  strcpy(dirTemp, dirName);
  strcpy(timestampTemp, timestamp);

  strcpy(fileName, mergefile);
  strcpy(dirName, mergedir);

  save_fpc();

  strcpy(fileName, fileTemp);
  strcpy(dirName, dirTemp);
  strcpy(timestamp, timestampTemp);

  if (dirName[0]=='\0' && mergedir[0]!=0){
   sprintf(buf,"cp %s.cor %s/%s.cor", fileName, mergedir, mergefile);
  }
  else if (dirName[0]=='\0' && mergedir[0]==0){
   sprintf(buf,"cp %s.cor %s.cor", fileName,  mergefile);
  }
  else if (dirName[0]!='\0' && mergedir[0]==0){
   sprintf(buf,"cp %s/%s.cor %s.cor", dirName, fileName, mergefile);
  }
  else{
   sprintf(buf,"cp %s/%s.cor %s/%s.cor", dirName, fileName, mergedir,mergefile);
  }
  printf("%s\n",buf);
  system(buf);
}
